<?php

namespace app\order\logic;

use app\reporting\logic\ReportVisitLogic;
use think\facade\Db;
use think\facade\Cache;
use util\Excel;
use think\exception\ValidateException;
use think\facade\Log;
use util\Token;
use util\Upload;
use think\cache\driver\Redis;
use app\order\logic\OrderSourceLogic;
use app\order\logic\OrderReportDailyLogic;

class OrderReportDataScreenLogic
{

    public function __construct()
    {

    }

    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @desc 列表
     * @author zhangheng
     */
    public function index($params = [])
    {

        $admin_id     = $params['admin_id']??'';
        //是否管理员
        $admin_group_id     = $params['admin_group_id']??'';
        if($admin_group_id==1){
            //spu销量排行
            $SpuRanking         = $this->get_spu_info($admin_id);
            
            //广告排名
            // $AdvertisingRanking = $this->AdvertisingRanking();

            //订单数量增长曲线
            $OrderQuantity = $this->OrderQuantity($admin_id);

            //支付渠道排行
            $OperationalPerformance = $this->PaymentChannelRanking($admin_id);

            //今日昨日销售额--按店铺
            $daysSalesFigures = $this->TodayAndYesterdaysSalesFigures($admin_id);

            //数据统计
            $DataStatistics = $this->DataStatistics($admin_id);

            $data = [
                'SpuRanking' => $SpuRanking,
                // 'AdvertisingRanking' => $AdvertisingRanking,
                'OrderQuantity' => $OrderQuantity,
                'daysSalesFigures' => $daysSalesFigures,
                'OperationalPerformance' => $OperationalPerformance,
                'DataStatistics' => $DataStatistics,
            ];
        }else{
            $data = [
                'SpuRanking'             => [],
                'AdvertisingRanking'     => [],
                'OrderQuantity'          => [],
                'OperationalPerformance' => [],
                'daysSalesFigures' => [],
                'DataStatistics'         => [],
            ];
        }
        return json(DefaultResponse(200, true, '获取成功', $data));
    }


    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @desc 首页统计
     * @date 2024-08-02
     * @author zhangheng
     */
    public function statistics($params = [])
    {

        //是否管理员
        $admin_id     = $params['admin_id']??'';
        $admin_group_id     = $params['admin_group_id']??'';
        if($admin_group_id==1){
            //数据统计
            $DataStatistics = $this->DataStatistics($admin_id);

            $where = [];
            //实时
            $yesterday = date('Y-m-d', time() - timezone());
            $midnightYesterday = strtotime($yesterday . ' 00:00:00');
            $endOfYesterday  = strtotime($yesterday . ' 23:59:59');
            $where[]  = ['a.createtime', '>=', $midnightYesterday];
            $where[]  = ['a.createtime', '<=', $endOfYesterday];
            $where[]  = ['a.financial_status', 'in', ["partially_paid", "paid", "partially_refunded", "refunded"]];

            //负责人可以查看的店铺
            $OrderReportDailyLogic = new OrderReportDailyLogic();
            $shop_map = $OrderReportDailyLogic->PersonInCanView($admin_id);
            if($shop_map){
                $where[]  = ['a.shop_id', 'in', $shop_map];
            }

            //店铺SPU销量排行
            $StoreSalesRanking = $this->StoreSalesRanking($where);

            $list = [
                'DataStatistics'   =>$DataStatistics,
                'StoreSalesRanking'=>$StoreSalesRanking,
            ];
        }else if($admin_id == 131){
            //负责人 马珂彩
            //数据统计
            $DataStatistics = $this->DataStatistics($admin_id);

            $where = [];
            //实时
            $yesterday = date('Y-m-d', time() - timezone());
            $midnightYesterday = strtotime($yesterday . ' 00:00:00');
            $endOfYesterday  = strtotime($yesterday . ' 23:59:59');
            $where[]  = ['a.createtime', '>=', $midnightYesterday];
            $where[]  = ['a.createtime', '<=', $endOfYesterday];
            $where[]  = ['a.financial_status', 'in', ["partially_paid", "paid", "partially_refunded", "refunded"]];

            //负责人可以查看的店铺
            $OrderReportDailyLogic = new OrderReportDailyLogic();
            $shop_map = $OrderReportDailyLogic->PersonInCanView($admin_id);
            if($shop_map){
                $where[]  = ['a.shop_id', 'in', $shop_map];
            }

            //店铺SPU销量排行
            $StoreSalesRanking = $this->StoreSalesRanking($where);

            $list = [
                'DataStatistics'   =>$DataStatistics,
                'StoreSalesRanking'=>$StoreSalesRanking,
            ];
        }else if(in_array($admin_group_id,[11,17,20,19])){
            //数据统计
            $DataStatistics = $this->DataStatistics_operate($admin_id);

            $where = [];
            //实时
            $yesterday = date('Y-m-d', time() - timezone());
            $midnightYesterday = strtotime($yesterday . ' 00:00:00');
            $endOfYesterday  = strtotime($yesterday . ' 23:59:59');
            $where[]  = ['a.createtime', '>=', $midnightYesterday];
            $where[]  = ['a.createtime', '<=', $endOfYesterday];
            $where[]  = ['a.financial_status', 'in', ["partially_paid", "paid", "partially_refunded", "refunded"]];

            //店铺SPU销量排行
            $StoreSalesRanking = [];

            $list = [
                'DataStatistics'   =>$DataStatistics,
                'StoreSalesRanking'=>$StoreSalesRanking,
                'admin_group_id'=>$admin_group_id,
            ];
        }else{
            $list = [
                'DataStatistics'   =>[],
                'StoreSalesRanking'=>[],
            ];
        }
        return json(DefaultResponse(200, true, '获取成功', $list));
    }

    /**
    * @desc    店铺销量排行
    * @date    2024/7/31
    * @author  zhangheng
    */
    public function StoreSalesRanking($where)
    {
        $where[] = ['b.status', '<>',2];
        $list = Db::name('order_achievement')
            ->field('
                sum(a.total_price) as total_price,
                b.name as shop_name
            ')
            ->alias('a')
            ->join('qu_shops b','b.id = a.shop_id', 'left')
            ->where($where)
            ->where('a.total_price',">",0.001)
            ->group('a.shop_id')
            ->order('total_price desc')
            ->limit(10)
            ->select()
            ->toarray();
            
        return $list;
    }


    /**
     * @desc   获取昨日spu销量排行
     * @author luckyXiong
     * @date   2024-08-04
     */
    public function get_spu_info($admin_id = 0){
        $where       = [];
        $limit       = 20;
        $yesterday   = date('Y-m-d', time() - timezone());
        $time_start  = strtotime($yesterday . ' 00:00:00');
        $time_end    = strtotime($yesterday . ' 23:59:59');
        $where[]     = ['createtime','between', [$time_start, $time_end]];
        $where[]     = ['financial_status', 'in', ["partially_paid", "paid", "partially_refunded", "refunded"]];

        //负责人可以查看的店铺
        $OrderReportDailyLogic = new OrderReportDailyLogic();
        $shop_map = $OrderReportDailyLogic->PersonInCanView($admin_id);
        if($shop_map){
            $where[]  = ['shop_id', 'in', $shop_map];
        }

        $where[]  = ['is_seel', '<>', 1];
        
        $list = Db::name('order_skuinfo')
            ->field('
                sum(realcount) as skuquantity,
                spu,
                order_id,
                createtime
            ')
            ->where($where)
            ->group('spu')
            ->order('skuquantity desc')
            ->paginate($limit);

        $lists = $list->items();




        //批量获取sku图片;
        $spus       = array_column($lists,'spu');
        $order_ids  = array_column($lists,'order_id');

        //批量获取图片地址;
        $products     = Db::name('product_inventory')->field('spu,product_images')->whereIn('spu',$spus)->select()->toArray();
        $products_map = array_column($products,null,'spu');
        $product_names= Db::name('product')->field('spu,product_name,product_images')->whereIn('spu',$spus)->select()->toArray();
        $products_name_map = array_column($product_names,null,'spu');

        //获取总的spu;
        $spu_info =Db::name('order_skuinfo')
            ->field('sum(realcount) as skuquantity')
            ->where($where)
            ->group('spu')
            ->select()
            ->toArray();

        //前一天的销量
        // $where_last       = [];
        // $yesterday   = date('Y-m-d', time() - timezone() - 24*3600);
        // $time_start  = strtotime($yesterday . ' 00:00:00');
        // $time_end    = strtotime($yesterday . ' 23:59:59');
        // $where_last[]     = ['c.createtime','between', [$time_start, $time_end]];
        // $where_last[]     = ['c.financial_status', 'in', ["partially_paid", "paid", "partially_refunded", "refunded"]];
        // $where_last[]     = ['a.spu', 'in', $spus];
        // $list_last = Db::name('order_skuinfo')
        //     ->field('
        //         sum(a.realcount) as skuquantity,
        //         a.spu
        //     ')
        //     ->alias('a')
        //     ->join('qu_order c','a.order_id = c.order_id', 'left')
        //     ->where($where_last)
        //     ->group('a.spu')
        //     ->order('skuquantity desc')
        //     ->select()->toarray();
        // $spus_last = array_column($list_last,'skuquantity','spu');
        // //前一天的销量
        // //前两天的销量
        // $where_lasttwo       = [];
        // $yesterday   = date('Y-m-d', time() - timezone() - 24*3600*2);
        // $time_start  = strtotime($yesterday . ' 00:00:00');
        // $time_end    = strtotime($yesterday . ' 23:59:59');
        // $where_lasttwo[]     = ['c.createtime','between', [$time_start, $time_end]];
        // $where_lasttwo[]     = ['c.financial_status', 'in', ["partially_paid", "paid", "partially_refunded", "refunded"]];
        // $where_lasttwo[]     = ['a.spu', 'in', $spus];
        // $list_lasttwo = Db::name('order_skuinfo')
        //     ->field('
        //         sum(a.realcount) as skuquantity,
        //         a.spu
        //     ')
        //     ->alias('a')
        //     ->join('qu_order c','a.order_id = c.order_id', 'left')
        //     ->where($where_lasttwo)
        //     ->group('a.spu')
        //     ->order('skuquantity desc')
        //     ->select()->toarray();
        // $spus_lasttwo = array_column($list_lasttwo,'skuquantity','spu');
        //前两天的销量

        $spu_nums = array_sum(array_column($spu_info, 'skuquantity'));
        foreach ($lists as $k=>$v) {
            $product_images_inquiry    = $products_map[$v['spu']]??[];
            $product_images_product    = $products_name_map[$v['spu']]??[];
            $product_name              = $product_images_product['product_name']??'';
            if(!$product_name)           $product_name = '女士内衣';
            $lists[$k]['product_name'] = $product_name;
            $product_images            = $product_images_product['product_images']??[];
            $display_images            = $product_images ? current(json_decode($product_images)) : '';
            if(!$display_images) {
                $display_images        = $product_images_inquiry['product_images']??'';
            }
            $lists[$k]['product_images'] = $display_images;
            $price_info   = self::get_spu_price($v['spu']);
            if($v['skuquantity'] && $price_info){
                $lists[$k]['spu_sales'] = '$'.getRes($v['skuquantity']*$price_info);
            }else{
                $lists[$k]['spu_sales'] = '';
            }
            $lists[$k]['total_price']  = $price_info ?  '$'.$price_info : '';
            if($v['skuquantity']){
                $rate = $v['skuquantity']/$spu_nums;
                $rate = getRes($rate*100);
                $lists[$k]['spu_rate'] = $rate.'%';
            }else{
                $lists[$k]['spu_rate'] = '';
            }
            $lists[$k]['createtime']   = $v['createtime'] ? date("Y-m-d H:i:s", $v['createtime']) : '';
            //增长率
            // $lists[$k]['skuquantity_last'] = $spus_last[$v['spu']];
            // $Difference = $v['skuquantity'] - $lists[$k]['skuquantity_last'];
            // //今日刚转点 增长率小于0的话 用前两天的销量对比
            // if($Difference > 0){
            //     $lists[$k]['GrowthRate'] = $Difference / $lists[$k]['skuquantity_last'] * 100;
            //     $lists[$k]['GrowthRate'] = getRes($lists[$k]['GrowthRate'])."%" ?? "0%";
            // }else{
            //     $lists[$k]['skuquantity_lasttwo'] = $spus_lasttwo[$v['spu']];
            //     $lists[$k]['GrowthRate'] = ($lists[$k]['skuquantity_last'] - $lists[$k]['skuquantity_lasttwo']) / $lists[$k]['skuquantity_lasttwo'] * 100;
            //     $lists[$k]['GrowthRate'] = getRes($lists[$k]['GrowthRate'])."%" ?? "0%";
            // }
        }
        return  $lists;
    }


    /**
    * @desc    广告排名
    * @date    2024/7/31
    * @author  zhangheng
    */
    public function AdvertisingRanking()
    {
        //实时
        $yesterday = date('Y-m-d', time() - timezone() - 24*3600);  
        $midnightYesterday = strtotime($yesterday . ' 00:00:00');
        $where[]  = ['a.stat_time', '=', $midnightYesterday];
        
        $list = Db::name('advertising')  
            ->field('  
                sum(a.spend) as spend,  
                d.nickname as advertiser_id
            ')  
            ->alias('a')  
            ->join('qu_advaccount b', 'b.advertiser_id = a.advertiser_id', 'left')  
            ->join('qu_advaccount_admin c', '  
                c.advertiser_id = b.advertiser_id AND  
                c.createtime <= a.stat_time AND  
                c.updatetime > a.stat_time AND  
                c.status = 0', 'left')  
            ->join('qu_advaccount_admin c2', '  
                c2.advertiser_id = b.advertiser_id AND  
                c2.createtime <= a.stat_time AND  
                c2.status = 1', 'left')  
            ->join('qu_system_admin d', 'd.id = COALESCE(c.admin_id, c2.admin_id)', 'left') 
            ->where($where)
            ->where(function ($query) {  
                $query->where('COALESCE(c.admin_id, c2.admin_id) IS NOT NULL');  
            })  
            ->group('COALESCE(c.admin_id, c2.admin_id)')  
            ->order("spend desc")  
            ->limit(10)
            ->select()->toArray();
        return $list;
    }
    /**
    * @desc    订单数量增长曲线
    * @date    2024/7/31
    * @author  zhangheng
    */
    public function OrderQuantity($admin_id = 0)
    {
        $yesterday = strtotime(date('Y-m-d', time() + 3600*24 - timezone()));  
        $yesterdayEnd = strtotime(date('Y-m-d', strtotime('-8 day') - timezone()));  
        $where[] = ['createtime', '<=', $yesterday];
        $where[] = ['createtime', '>=', $yesterdayEnd];
        $where[]  = ['financial_status', 'in', ["partially_paid", "paid", "partially_refunded", "refunded"]];
        //负责人可以查看的店铺
        $OrderReportDailyLogic = new OrderReportDailyLogic();
        $shop_map = $OrderReportDailyLogic->PersonInCanView($admin_id);
        if($shop_map){
            $where[]  = ['shop_id', 'in', $shop_map];
        }
        $list = Db::name('order_achievement')  
            ->field('DATE(FROM_UNIXTIME(createtime)) as date, COUNT(id) as quantity')  
            ->group('date')  
            ->where($where)
            ->order('date asc')
            ->limit(10)
            ->select()  
            ->toArray();
            
        foreach ($list as $key=>$item) {  
            $item['date'] = $this->getWeekdayChinese($item['date']); 
            if($key == 0 || $key == 1){
                $list[$key]['date'] = "上".$item['date'];
            }else{
                $list[$key]['date'] = $item['date'];
            }
        } 
        return $list;
    }

    // 切换成周  
    public function getWeekdayChinese($dateString) {  
        date_default_timezone_set('Asia/Shanghai');
        $timestamp = strtotime($dateString);  
        $timestamp = date('l', $timestamp); 
        switch ($timestamp) {
            case 'Saturday':
                $timestamp = '周六';
                break;
            case 'Sunday':
                $timestamp = '周日';
                break;
            case 'Monday':
                $timestamp = '周一';
                break;
            case 'Tuesday':
                $timestamp = '周二';
                break;
            case 'Wednesday':
                $timestamp = '周三';
                break;
            case 'Thursday':
                $timestamp = '周四';
                break;
            case 'Friday':
                $timestamp = '周五';
                break;
            default:
                $timestamp = '未知';
        }
        
        return $timestamp;  
    }  
    /**
    * @desc    运营业绩
    * @date    2024/7/31
    * @author  zhangheng
    */
    public function OperationalPerformance()
    {
        //实时
        $start_time = date('Y-m-01', strtotime('-1 month'));
        $end_time = date('Y-m-d 23:59:59', strtotime(-date('d') . 'day'));
        $where[]  = ['a.createtime', '>=', strtotime($start_time)];
        $where[]  = ['a.createtime', '<=', strtotime($end_time)];
        $where[]  = ['a.financial_status', 'in', ["partially_paid", "paid", "partially_refunded", "refunded"]];
        $where[]  = ['a.shop_id', '=', 17];
        $where[]  = ['a.tag_campaign', '<>', "LabelIsEmpty"];

        $lists = Db::name('order_source')
            ->field('SUM(b.total_price) as total_price,a.tag_campaign')
            ->alias('a')
            ->join('qu_order_achievement b','b.order_id = a.order_id', 'left')
            ->where($where)
            ->group('a.tag_campaign')
            ->select()
            ->toarray();
        $OrderSourceLogic = new OrderSourceLogic();
        foreach ($lists as $k=>$v) {
            $lists[$k]['tag_campaign'] = $OrderSourceLogic->tag_campaign($v['tag_campaign']);
        }

        return $lists;
    }

    /**
    * @desc    支付渠道排行
    * @date    2024/8/19
    * @author  zhangheng
    */
    public function PaymentChannelRanking($admin_id = 0)
    {
        //实时
        $yesterday = date('Y-m-d', time() - timezone());  
        $midnightYesterday = strtotime($yesterday . ' 00:00:00');
        $endOfYesterday  = strtotime($yesterday . ' 23:59:59');
        $where[]  = ['createtime', '>=', $midnightYesterday];
        $where[]  = ['createtime', '<=', $endOfYesterday];
        $where[]  = ['financial_status', 'in', ["partially_paid", "paid", "partially_refunded", "refunded"]];
        //负责人可以查看的店铺
        $OrderReportDailyLogic = new OrderReportDailyLogic();
        $shop_map = $OrderReportDailyLogic->PersonInCanView($admin_id);
        if($shop_map){
            $where[]  = ['shop_id', 'in', $shop_map];
        }
        
        // $StartTime = strtotime(date('Y-m-d', strtotime('-6 days')));
        // $where[]  = ['financial_status', 'in', ["partially_paid", "paid", "partially_refunded", "refunded"]];
        $lists = Db::name('order_achievement')
            ->field('SUM(total_price) as total_price,payment_gateway_names as tag_campaign')
            ->where($where)  
            ->group('payment_gateway_names')
            ->order('total_price desc')
            ->select()
            ->toarray();
            // 计算总和  
        $totalSum = array_sum(array_column($lists, 'total_price'));  

        foreach ($lists as $k=>$v) {
            if(empty($v['tag_campaign'])){
                $lists[$k]['tag_campaign'] = "其他通道";
            }
            //占比
            $percentage = ($v['total_price'] / $totalSum) * 100;  
            $lists[$k]['percentage'] = round($percentage, 2)."%";  
        }
            
        return $lists;
    }

    /**
    * @desc    数据统计
    * @date    2024/7/31
    * @author  zhangheng
    */
    public function DataStatistics($admin_id = 0)
    {
        //负责人可以查看的店铺
        $OrderReportDailyLogic = new OrderReportDailyLogic();
        $shop_map = $OrderReportDailyLogic->PersonInCanView($admin_id);

        //汇率-----使用最新的汇率
        $order_exchange = Db::name('order_exchange')->order('date desc')->find();

        //实时
        $yesterday = date('Y-m-d', time() - timezone());  
        $midnightYesterday = strtotime($yesterday . ' 00:00:00');
        $endOfYesterday  = strtotime($yesterday . ' 23:59:59');
        $where[]  = ['a.createtime', '>=', $midnightYesterday];
        $where[]  = ['a.createtime', '<=', $endOfYesterday];
        $where[]  = ['a.financial_status', 'in', ["partially_paid", "paid", "partially_refunded", "refunded"]];

        if(!empty($shop_map)){
            $where[] = ['a.shop_id', 'in', $shop_map];
        }else{
            $where[] = ['a.shop_id', '<>', 19];
        }

        $list = Db::name('order_achievement')
            ->field('
                COUNT(a.id) as quantity,
                sum(a.total_price) as total_price,
                sum(a.skuquantity) as skuquantity,
                sum(a.estimate_freight) as estimate_freight,
                sum(a.material) as material
            ')
            ->alias('a')
            ->where($where)
            ->select()->toarray();

        $where = [];
        $yesterday = date('Y-m-d', time() - timezone() - 24*3600);  
        $midnightYesterday = strtotime($yesterday . ' 00:00:00');
        $endOfYesterday  = strtotime($yesterday . ' 23:59:59');
        $where[]  = ['a.createtime', '>=', $midnightYesterday];
        $where[]  = ['a.createtime', '<=', $endOfYesterday];
        $where[]  = ['a.financial_status', 'in', ["partially_paid", "paid", "partially_refunded", "refunded"]];
        if(!empty($shop_map)){
            $where[] = ['a.shop_id', 'in', $shop_map];
        }
        //昨日数据
        $list_last = Db::name('order_achievement')
            ->field('
                COUNT(a.id) as quantity,
                sum(a.total_price) as total_price,
                sum(a.skuquantity) as skuquantity,
                sum(a.estimate_freight) as estimate_freight,
                sum(a.material) as material
            ')
            ->alias('a')
            ->where($where)
            ->select()->toarray();

        //实时广告
        $where = [];
        $yesterday = date('Y-m-d', time() - timezone());  
        $midnightYesterday = strtotime($yesterday . ' 00:00:00');
        $endOfYesterday  = strtotime($yesterday . ' 23:59:59');
        $where[]  = ['stat_time', '>=', $midnightYesterday];
        $where[]  = ['stat_time', '<=', $endOfYesterday];
        //保险费
        $where_premium = [];
        $where_premium[]  = ['b.createtime', '>=', $midnightYesterday];
        $where_premium[]  = ['b.createtime', '<=', $endOfYesterday];
        $premium_price = Db::name('order_info')
            ->field('sum(a.price) as premium_price')
            ->alias('a')
            ->join('qu_order_achievement b','b.order_id = a.order_id', 'left')
            ->where($where_premium)
            ->where('a.is_seel',1)
            ->select()
            ->toarray();
        $list[0]['premium_price'] = $premium_price[0]['premium_price']??0;
        //保险费
        if(!empty($shop_map)){
            $where[] = ['shop_id', 'in', $shop_map];
        }
        $advertising = Db::name('advertising')
            ->field('
                sum(spend) as spend
            ')
            ->where($where)
            ->select()
            ->toarray();
        //昨日广告
        $where = [];
        $yesterday = date('Y-m-d', time() - timezone() - 24*3600);  
        $midnightYesterday = strtotime($yesterday . ' 00:00:00');
        $endOfYesterday  = strtotime($yesterday . ' 23:59:59');
        $where[]  = ['stat_time', '>=', $midnightYesterday];
        $where[]  = ['stat_time', '<=', $endOfYesterday];

        //保险费
        $where_premium = [];
        $where_premium[]  = ['b.createtime', '>=', $midnightYesterday];
        $where_premium[]  = ['b.createtime', '<=', $endOfYesterday];
        $premium_price = Db::name('order_info')
            ->field('sum(a.price) as premium_price')
            ->alias('a')
            ->join('qu_order_achievement b','b.order_id = a.order_id', 'left')
            ->where($where_premium)
            ->where('a.is_seel',1)
            ->select()
            ->toarray();
            
        $list_last[0]['premium_price'] = $premium_price[0]['premium_price']??0;
        //保险费
        
        if(!empty($shop_map)){
            $where[] = ['shop_id', 'in', $shop_map];
        }
        $advertising_last = Db::name('advertising')
            ->field('
                sum(spend) as spend
            ')
            ->where($where)
            ->select()
            ->toarray();
        $list[0]['advertising_spend'] = $advertising[0]['spend'] ?? 0;
        $list_last[0]['advertising_spend'] = $advertising_last[0]['spend'] ?? 0;

        $list = $this->profit($list,$order_exchange);
        $list_last = $this->profit($list_last,$order_exchange);

        $DataStatistics = [
            'DataStatisticsNew' => $list,
            'DataStatisticsLast' => $list_last,
        ];
        return $DataStatistics;
    }

    /**
    * @desc    实时记录今天业绩
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function profit($list,$order_exchange)
    {
        //ROI
        if ($list[0]['advertising_spend'] > 0.001 && $list[0]['total_price'] > 0.001) {
            $list[0]['roi'] = number_format((float)$list[0]['total_price'] / (float)$list[0]['advertising_spend'], 2, '.', '');
        }else{
            $list[0]['roi'] = 0;
        }
        //盈利
        //预估运费
        $list[0]['estimate_freight'] = getRes($list[0]['estimate_freight']/$order_exchange['dollar']);
        //预估采购
        $list[0]['material'] =  getRes($list[0]['material']/$order_exchange['dollar']);
        //退款
        $list[0]['refund'] = (float)number_format((float)$list[0]['total_price'] * 0.03, 2, '.', '');
        //平台佣金(预估6个点)
        $list[0]['PlatformCommission'] = (float)number_format((float)$list[0]['total_price'] * 0.06, 2, '.', '');
        $list[0]['premium_price'] = $list[0]['premium_price'] ?? 0;
        $list[0]['profit'] = number_format((float)$list[0]['total_price'] - (float)$list[0]['advertising_spend'] - (float)$list[0]['estimate_freight'] - (float)$list[0]['material'] - (float)$list[0]['refund'] - (float)$list[0]['PlatformCommission'] - $list[0]['premium_price'], 2, '.', '');
        $return = [
            'quantity' => $list[0]['quantity'] ?? 0,
            'advertising_spend' => $list[0]['advertising_spend'] ?? 0,
            'total_price' => $list[0]['total_price'] ?? 0,
            'skuquantity' => $list[0]['skuquantity'] ?? 0,
            'roi' => $list[0]['roi'] ?? 0,
            'profit' => $list[0]['profit'] ?? 0,
        ];
        return $return;
    }
    
    /**
    * @desc    
    * @date    2024/7/31
    * @author  zhangheng
    */
    public function DataStatistics_operate($admin_id)
    {
        $admin_id = $admin_id ?? 0;

        //实时广告
        $where = [];
        $yesterday = date('Y-m-d', time() - timezone());  
        $midnightYesterday = strtotime($yesterday . ' 00:00:00');
        $endOfYesterday  = strtotime($yesterday . ' 23:59:59');
        $where[]  = ['stat_time', '>=', $midnightYesterday];
        $where[]  = ['stat_time', '<=', $endOfYesterday];
        $where[]  = ['admin_id', '=', $admin_id];

        $advertising = Db::name('advertising')
            ->field('
                sum(spend) as spend,shop_id
            ')
            ->where($where)
            ->select()
            ->toarray();
        //昨日广告
        $where = [];
        $yesterday = date('Y-m-d', time() - timezone() - 24*3600);  
        $midnightYesterday = strtotime($yesterday . ' 00:00:00');
        $endOfYesterday  = strtotime($yesterday . ' 23:59:59');
        $where[]  = ['stat_time', '>=', $midnightYesterday];
        $where[]  = ['stat_time', '<=', $endOfYesterday];
        $where[]  = ['admin_id', '=', $admin_id];

        $advertising_last = Db::name('advertising')
            ->field('
                sum(spend) as spend,shop_id
            ')
            ->where($where)
            ->select()
            ->toarray();
        
        $list['advertising_spend'] = $advertising[0]['spend'] ?? 0;
        $list_last['advertising_spend'] = $advertising_last[0]['spend'] ?? 0;
        
        $list['shop_id'] = $advertising[0]['shop_id'] ?? 0;
        $list_last['shop_id'] = $advertising_last[0]['shop_id'] ?? 0;
        //实时业绩
        $where = [];
        $yesterday = date('Y-m-d', time() - timezone());  
        $midnightYesterday = strtotime($yesterday . ' 00:00:00');
        $endOfYesterday  = strtotime($yesterday . ' 23:59:59');
        $where[]  = ['a.createtime', '>=', $midnightYesterday];
        $where[]  = ['a.createtime', '<=', $endOfYesterday];
        $where[]  = ['a.financial_status', 'in', ["partially_paid", "paid", "partially_refunded", "refunded"]];
        $where[]  = ['a.shop_id', '=', $list['shop_id']];

        $order_new = Db::name('order_achievement')
            ->field('
                COUNT(a.id) as quantity,
                sum(a.total_price) as total_price,
                sum(a.skuquantity) as skuquantity
            ')
            ->alias('a')
            ->where($where)
            ->select()->toarray();

        //昨日数据
        $where = [];
        $yesterday = date('Y-m-d', time() - timezone() - 24*3600);  
        $midnightYesterday = strtotime($yesterday . ' 00:00:00');
        $endOfYesterday  = strtotime($yesterday . ' 23:59:59');
        $where[]  = ['a.createtime', '>=', $midnightYesterday];
        $where[]  = ['a.createtime', '<=', $endOfYesterday];
        $where[]  = ['a.financial_status', 'in', ["partially_paid", "paid", "partially_refunded", "refunded"]];
        $where[]  = ['a.shop_id', '=', $list_last['shop_id']];
        
        $order_last = Db::name('order_achievement')
            ->field('
                COUNT(a.id) as quantity,
                sum(a.total_price) as total_price,
                sum(a.skuquantity) as skuquantity
            ')
            ->alias('a')
            ->where($where)
            ->select()->toarray();

        $list['quantity'] = $order_new[0]['quantity'] ?? 0;
        $list['total_price'] = number_format($order_new[0]['total_price'], 2);
        $list_last['quantity'] = $order_last[0]['quantity'] ?? 0;
        $list_last['total_price'] = number_format($order_last[0]['total_price'], 2);

        $DataStatistics = [
            'DataStatisticsNew' => $list,
            'DataStatisticsLast' => $list_last,
        ];
        return $DataStatistics;
    }


    /**
    * @desc    今日昨日销售额--按店铺
    * @date    2024/7/31
    * @author  zhangheng
    */
    public function TodayAndYesterdaysSalesFigures($admin_id = 0)
    {
        $where = [];
        //实时
        $yesterday = date('Y-m-d', time() - timezone());
        $midnightYesterday = strtotime($yesterday . ' 00:00:00');
        $endOfYesterday  = strtotime($yesterday . ' 23:59:59');
        $where[]  = ['a.createtime', '>=', $midnightYesterday];
        $where[]  = ['a.createtime', '<=', $endOfYesterday];
        $where[]  = ['a.financial_status', 'in', ["partially_paid", "paid", "partially_refunded", "refunded"]];
        //负责人可以查看的店铺
        $OrderReportDailyLogic = new OrderReportDailyLogic();
        $shop_map = $OrderReportDailyLogic->PersonInCanView($admin_id);
        if($shop_map){
            $where[]  = ['a.shop_id', 'in', $shop_map];
        }
        
        $StoreSalesRanking = $this->StoreSalesRanking($where);

        //昨日
        $where = [];
        $yesterday = date('Y-m-d', time() - timezone() - 24*3600);
        $midnightYesterday = strtotime($yesterday . ' 00:00:00');
        $endOfYesterday  = strtotime($yesterday . ' 23:59:59');
        $where[]  = ['a.createtime', '>=', $midnightYesterday];
        $where[]  = ['a.createtime', '<=', $endOfYesterday];
        $where[]  = ['a.financial_status', 'in', ["partially_paid", "paid", "partially_refunded", "refunded"]];
        
        if($shop_map){
            $where[]  = ['shop_id', 'in', $shop_map];
        }
        $StoreSalesRanking_yesterday = $this->StoreSalesRanking($where);
    
        
        $result = $this->mergeSalesArrays($StoreSalesRanking, $StoreSalesRanking_yesterday);
        return $result;
    }

    /**
    * @desc    实时记录今天业绩
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function mergeSalesArrays($array1, $array2)
    {
        $merged = [];
        foreach ($array1 as $item) { 
            $merged[$item['shop_name']]['Today'] = $item['total_price'];
        }
        
        foreach ($array2 as $item) {  
            $merged[$item['shop_name']]['Yesterday'] = $item['total_price'];
        }  
        
        // 转换回所需的格式  
        $result = [];  
        foreach ($merged as $shopName => $totalPrice) {  
            $result[] = [  
                "Today" => $totalPrice['Today'] ?? 0,
                "Yesterday" => $totalPrice['Yesterday'] ?? 0,
                "shopname" => $shopName  
            ];  
        }  
        return $result;  
    }
    

    /**
     * @desc    获取spu单价
     * @date    2024/8/22
     * @author  luckyXiong
     */
    public function get_spu_price($spu=''){
         $res =  Db::name('order_spu_price')->where(['spu'=>$spu])->value('price');
         if(!$res){
             $res = '28.26';
         }
         return  $res;
    }


    /**
     * @desc   查看当前页面
     * @author luckyXiong
     * @date   2025-04-28
     */
    public function getRoleType($params=[]){
        $adminId   = $params['adminId']??'';
        //查看当前在职运营
        $exist_info= Db::name('order_page_shop_admin')->where(['admin_id'=>$adminId])->find();
        if($exist_info && $adminId!='131'){
                 return  1;
        }else{
                 return  2;
        }
    }


    /**
     * @desc   获取新首页数据
     * @author luckyXiong
     * @date   2025-04-28
     */
    public function new_statistics($params=[]){
        $admin_id          = $params['adminId']??'';
        $where = $map      = [];
        //获取当天广告花费
        $yesterday         = date('Y-m-d', time() - timezone());
        $midnightYesterday = strtotime($yesterday . ' 00:00:00');
        $endOfYesterday    = strtotime($yesterday . ' 23:59:59');
        $where[] = ['stat_time', '>=', $midnightYesterday];
        $where[] = ['stat_time', '<=', $endOfYesterday];
        $where[] = ['admin_id', '=', $admin_id];
        $spend_today = Db::name('advertising')
            ->field('id,advertiser_id,spend')
            ->where($where)
            ->select()
            ->toarray();
        $spend_now = array_sum(array_column($spend_today,'spend'));

        //获取昨天广告花费
        $yesterday         = date('Y-m-d', strtotime('-1 day') - timezone());
        $midnightYesterday = strtotime($yesterday . ' 00:00:00');
        $endOfYesterday    = strtotime($yesterday . ' 23:59:59');
        $map[] = ['stat_time', '>=', $midnightYesterday];
        $map[] = ['stat_time', '<=', $endOfYesterday];
        $map[] = ['admin_id', '=', $admin_id];
        $spend_yestoday = Db::name('advertising')
            ->field('id,advertiser_id,spend,platform_id')
            ->where($map)
            ->select()
            ->toarray();
        $spend_yes = array_sum(array_column($spend_yestoday,'spend'));

        $spend_now = $spend_now ? getRes($spend_now) : '0.00';
        $spend_yes = $spend_yes ? getRes($spend_yes) : '0.00';

        $current_info = current($spend_yestoday);

        return [
             'spend_now'           =>$spend_now??'0.00',
             'spend_yes'           =>$spend_yes??'0.00',
             'platform_first_id'   =>$current_info['platform_id']??'1',
        ];
    }




    
}
